package com.qfhd.soft.cjzcore.UI;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jaeger.library.StatusBarUtil;
import com.qfhd.soft.cjzcore.CJZManager;
import com.qfhd.soft.cjzcore.Core.CJCore;
import com.qfhd.soft.cjzcore.Core.CJFile;
import com.qfhd.soft.cjzcore.Core.CJHttpDownloadInfo;
import com.qfhd.soft.cjzcore.Core.CJLogger;
import com.qfhd.soft.cjzcore.Core.CJTime;
import com.qfhd.soft.cjzcore.Core.CJWatcher;
import com.qfhd.soft.cjzcore.Handle.CJHandle;
import com.qfhd.soft.cjzcore.Handle.CJHandleObject;
import com.qfhd.soft.cjzcore.Handle.CJHanlderType;
import com.qfhd.soft.cjzcore.Handle.CJHanlderWhatType;
import com.qfhd.soft.cjzcore.Model.Task_try_detail_model;
import com.qfhd.soft.cjzcore.Model.Task_try_detail_section_model;
import com.qfhd.soft.cjzcore.Moudle.CJTryPlaceHelper;
import com.qfhd.soft.cjzcore.R;
import com.qfhd.soft.cjzcore.UI.Base.BaseActivity;
import com.qfhd.soft.cjzcore.UI.Core.CJActivityManager;
import com.qfhd.soft.cjzcore.UI.Core.CJPackage;
import com.qfhd.soft.cjzcore.UI.Dialog.CJDialog;
import com.qfhd.soft.cjzcore.UI.Dialog.CJSignDialog;
import com.qfhd.soft.cjzcore.UI.Dialog.MessageDialog;
import com.qfhd.soft.cjzcore.UI.Listener.CJListener;
import com.qfhd.soft.cjzcore.download.CJDownloadInfo;
import com.qfhd.soft.cjzcore.download.limit.CJDownloadLimitManager;
import com.qmuiteam.qmui.layout.QMUILinearLayout;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.util.Collections;

import static com.qfhd.soft.cjzcore.Handle.CJHanlderWhatType.DownLoad_ing;
import static com.qfhd.soft.cjzcore.Handle.CJHanlderWhatType.DownLoad_sucess;
import static com.qfhd.soft.cjzcore.Handle.CJHanlderWhatType.Download;
import static com.qfhd.soft.cjzcore.Handle.CJHanlderWhatType.Download_failed;
import static com.qfhd.soft.cjzcore.Handle.CJHanlderWhatType.LoadFailed;
import static com.qfhd.soft.cjzcore.Handle.CJHanlderWhatType.LoadFinish;

public class TryTaskDetailActivity extends BaseActivity {
    //    @BindView(R.id.try_task_detail_back)
    ImageView navi_back;
//    @BindView(R.id.try_task_detail_icon)
    QMUIRadiusImageView apk_icon;

//    @BindView(R.id.try_task_detail_title)
    TextView apk_title;

//    @BindView(R.id.try_task_detail_subTitle)
    TextView apk_size;

//    @BindView(R.id.try_task_detail_isPackage)
    TextView apk_isPackage;

//    @BindView(R.id.try_task_detail_coin)
    TextView apk_coin;

//    @BindView(R.id.try_task_detail_point_one)
    View point_first;
//    @BindView(R.id.try_task_detail_point_second)
    View point_second;
//    @BindView(R.id.trt_task_detail_point_thrid)
    View point_thirth;
//    @BindView(R.id.try_task_detail_point_fourth)
    View point_fourth;
//    @BindView(R.id.try_task_detail_tip)
    TextView tx_tip;
//    @BindView(R.id.try_task_detail_secont_first_subTitle)
    TextView section_first_subTitle;
//    @BindView(R.id.try_task_detail_secont_first_status)
    TextView section_first_status;
//    @BindView(R.id.try_task_detail_secont_first_status_layout)
    LinearLayout section_first_status_layout;
//    @BindView(R.id.try_task_detail_secont_second_title)
    TextView section_second_title;
//    @BindView(R.id.try_task_detail_secont_second_subTitle)
    TextView section_second_subtitle;
//    @BindView(R.id.try_task_detail_secont_second_status)
    TextView section_second_status;

//    @BindView(R.id.try_task_detail_secont_second_status_layout)
    LinearLayout section_second_status_layout;

//    @BindView(R.id.try_task_detail_secont_thirth_title)
    TextView section_thirth_title;

//    @BindView(R.id.try_task_detail_secont_thirth_subTitle)
    TextView section_thirth_subtitle;

//    @BindView(R.id.try_task_detail_secont_thirth_status)
    TextView section_thirth_status;

//    @BindView(R.id.try_task_detail_secont_thirth_status_layout)
    LinearLayout section_thirth_status_layout;

//    @BindView(R.id.try_task_detail_begin)
    QMUILinearLayout task_begin;

//    @BindView(R.id.try_task_detail_progressbar)
    ProgressBar progressBar;

//    @BindView(R.id.try_task_detail_begin_text)
    TextView tx_begin_text;


    private final int STATE_Doing = 0;
    private final int STATE_Done = 1;
    private final int STATE_Finish = 2;
    private final int STATE_Can = 5;


    private Context mContext;
    private Activity mActivity;
    private Task_try_detail_model data;
    private QMUITipDialog waitDialog;
    private CJHttpDownloadInfo taskInfo = new CJHttpDownloadInfo();
    private int section = 0;
    private CJSignDialog rewardDialog;
    private String tid;
    CJDownloadInfo info;
    private MessageDialog myMessageDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_try_task_detail);
        mActivity = this;
        mContext = this;
        CJHandle.getInstance().register(new CJHandleObject(CJHanlderType.tryPlace,myHandler));
        StatusBarUtil.setColor(this, getResources().getColor(R.color.white), 0);
        QMUIStatusBarHelper.setStatusBarLightMode(mActivity);
//        task_begin.setRadiusAndShadow(30,10,0.25f);//阴影

        navi_back = findViewById(R.id.try_task_detail_back);
        apk_title = findViewById(R.id.try_task_detail_title);
        apk_icon = findViewById(R.id.try_task_detail_icon);
        apk_size = findViewById(R.id.try_task_detail_subTitle);
        apk_isPackage = findViewById(R.id.try_task_detail_isPackage);
        apk_coin = findViewById(R.id.try_task_detail_coin);
        tx_tip = findViewById(R.id.try_task_detail_tip);
        section_first_subTitle = findViewById(R.id.try_task_detail_secont_first_subTitle);
        section_first_status = findViewById(R.id.try_task_detail_secont_first_status);
        section_first_status_layout = findViewById(R.id.try_task_detail_secont_first_status_layout);
        section_second_title = findViewById(R.id.try_task_detail_secont_second_title);
        section_second_subtitle = findViewById(R.id.try_task_detail_secont_second_subTitle);
        section_second_status = findViewById(R.id.try_task_detail_secont_second_status);
        section_second_status_layout = findViewById(R.id.try_task_detail_secont_second_status_layout);
        section_thirth_title = findViewById(R.id.try_task_detail_secont_thirth_title);
        section_thirth_subtitle = findViewById(R.id.try_task_detail_secont_thirth_subTitle);
        section_thirth_status = findViewById(R.id.try_task_detail_secont_thirth_status);
        section_thirth_status_layout = findViewById(R.id.try_task_detail_secont_thirth_status_layout);
        task_begin = findViewById(R.id.try_task_detail_begin);
        progressBar = findViewById(R.id.try_task_detail_progressbar);
        tx_begin_text = findViewById(R.id.try_task_detail_begin_text);

        waitDialog = CJDialog.getTipDialog(CJDialog.CJDialog_TIP_TYPE_LOADING, mContext, "加载中");

        tid = getIntent().getStringExtra(CJActivityManager.Intent_Name_String);

        loadData();
        initEvent();
    }

    private void initUi() {
        CJWatcher.getInstance().setPackagename(data.package_name);
        navi_back.setOnClickListener(v -> back());
        Glide.with(mContext).load(data.apk_icon).placeholder(R.drawable.placeholder).centerCrop().into(apk_icon);
        apk_title.setText(data.apk_name);
        apk_size.setText(CJFile.getFileSieze(data.file_size));
        tx_tip.setText(data.operate_note);
        if (CJPackage.isPackageInstalled(mContext, data.package_name)) {
            apk_isPackage.setText("已安装");
        } else {
            apk_isPackage.setText("未安装");
        }
        apk_coin.setText("共+" + data.full_reward + "金币");


        for (int i = 0; i < data.sections.size(); i++) {
            Task_try_detail_section_model section = data.sections.get(i);
            int count = section.days-1;
            if (i == 0) {
                if (isNotDone(section.state)) {
                    section_first_status_layout.setEnabled(false);
                    section_first_status_layout.setBackground(getResources().getDrawable(R.drawable.radius_20_gray));
                    section_first_status.setText("未完成");
                } else {
                    section_first_status_layout.setEnabled(true);
                    section_first_status_layout.setBackground(getResources().getDrawable(R.drawable.radius_20_theme));
                    section_first_status.setText("已完成");
                }
                section_first_subTitle.setText("+" + section.section_reward + "金币");
            }

            if (i == 1) {
                section_second_title.setText(CJTime.getTimeFormatMMDD((data.apply_at + count * 24 * 60 * 60) * 1000));
                if (isNotDone(section.state)) {
                    section_second_status_layout.setEnabled(false);
                    section_second_status_layout.setBackground(getResources().getDrawable(R.drawable.radius_20_gray));
                    section_second_status.setText("未完成");
                } else {
                    section_second_status_layout.setEnabled(true);
                    section_second_status_layout.setBackground(getResources().getDrawable(R.drawable.radius_20_theme));
                    section_second_status.setText("已完成");
                }
                section_second_subtitle.setText("+" + section.section_reward + "金币");
            }

            if (i == 2) {
                section_thirth_title.setText(CJTime.getTimeFormatMMDD((data.apply_at + count * 24 * 60 * 60) * 1000));
                if (isNotDone(section.state)) {
                    section_thirth_status_layout.setEnabled(false);
                    section_thirth_status_layout.setBackground(getResources().getDrawable(R.drawable.radius_20_gray));
                    section_thirth_status.setText("未完成");
                } else {
                    section_thirth_status_layout.setEnabled(true);
                    section_thirth_status_layout.setBackground(getResources().getDrawable(R.drawable.radius_20_theme));
                    section_thirth_status.setText("已完成");
                }
                section_thirth_subtitle.setText("+" + section.section_reward + "金币");
            }
        }

        //如果当日任务完成 就提示退出
//        section = 0;
        this.section = getSection();
        if(this.section == -1){
            MessageDialog.dialogShow(mActivity,mContext, "温馨提示"
                    , "任务过期",v ->{
                        back();
                    });
        }
        else if(this.section == -2){
            MessageDialog.dialogShow(mActivity,mContext, "温馨提示"
                    , "当日无任务",v ->{
                        back();
                    });
        }
        else {
            if (!isNotDone(data.sections.get(section).state)) {
                MessageDialog.dialogShow(mActivity,mContext, "温馨提示"
                        , "当日 【" + data.apk_name + "】 任务已完成", v -> {
                            back();
                        });
            }
        }
    }

    private void initEvent() {
        task_begin.setOnClickListener(v -> {
            if(!checkUsagePermission()){
                CJLogger.v("");
                return;
            }
            for (int i = 0; i < data.sections.size(); i++) {
                Task_try_detail_section_model section = data.sections.get(i);
                if (section.days == 1) { //试玩
                    //是否已经下载完成
                    //下载安装，试玩
                    //时长是否满足
                    if (isNotDone(section.state)) {
                        task_begin.setEnabled(true);
                        task_begin.setBackground(getResources().getDrawable(R.drawable.radius_30_theme));
                        if(info == null){ //未下载的状态
                            if (CJPackage.isPackageInstalled(mContext, data.package_name)) {
                                CJPackage.launchApk(mActivity, data.package_name);
                                CJWatcher.getInstance().putWatch(data.package_name);
                                CJWatcher.getInstance().setTime(data.package_name);
                            } else {
                                download();
                            }
                        }
                        else{
                            if (info.getUrl() != data.apk_url){
                                return;
                            }
                            if (CJDownloadInfo.DOWNLOAD_OVER.equals(info.getDownloadStatus())){
                                if (CJPackage.isPackageInstalled(mContext, data.package_name)) {
                                    CJPackage.launchApk(mActivity, data.package_name);
                                    CJWatcher.getInstance().putWatch(data.package_name);
                                    CJWatcher.getInstance().setTime(data.package_name);
                                }
                                else{
                                    CJPackage.installApk(mContext,CJFile.getInstance().getDataFolder() + "/" +info.getFileName());
                                }
                            }
                            if(CJDownloadInfo.DOWNLOAD.equals(info.getDownloadStatus())){
                                mActivity.runOnUiThread(()->{
                                    CJCore.Toast(mContext,"暂停",false);});
                                CJDownloadLimitManager.getInstance().pauseDownload(info.getUrl());
                            }
                            else if (CJDownloadInfo.DOWNLOAD_PAUSE.equals(info.getDownloadStatus())){
                                mActivity.runOnUiThread(()->{CJCore.Toast(mContext,"开始下载",false);});
                                CJDownloadLimitManager.getInstance().download(info.getUrl());
                            }
                        }
                    }
                    else{
                        if(getSection() == section.days) {
                            task_begin.setEnabled(false);
                            task_begin.setBackground(getResources().getDrawable(R.drawable.radius_30_gray));
                            MessageDialog.dialogShow(mActivity,mContext, "任务", "当日任务已完成");
                            break;
                        }
                    }
                }

                if(section.days >= 2) {
                    if (isNotDone(section.state)) {
                        task_begin.setEnabled(true);
                        task_begin.setBackground(getResources().getDrawable(R.drawable.radius_30_theme));
                        if (CJPackage.isPackageInstalled(mContext, data.package_name)) {
                            CJPackage.launchApk(mContext, data.package_name);
                            CJWatcher.getInstance().putWatch(data.package_name);
                            CJWatcher.getInstance().setTime(data.package_name);
                        }
                        else{
                            MessageDialog.dialogShow(mActivity,mContext,"任务","无法打开：" + data.apk_name);
                        }
                        break;
                    }
                    else{
                        if(getSection() == section.days){
                            task_begin.setEnabled(false);
                            task_begin.setBackground(getResources().getDrawable(R.drawable.radius_30_gray));
                            MessageDialog.dialogShow(mActivity,mContext,"任务","当日任务已完成");
                            break;
                        }
                    }
                }
            }
        });
    }

    private void reportSectionTask(Task_try_detail_section_model model) {
        waitDialog.show();
        new Thread(() -> {
            boolean ret = CJZManager.getInstance().tryPlaceReport(data.tid, data.sections.get(section).task_id, data.sections.get(section).section_id);
            if (ret) {
                mActivity.runOnUiThread(() -> {
                    waitDialog.dismiss();
                    rewardDialog = new CJSignDialog(mActivity,mContext, data.sections.get(section).section_reward);
                    rewardDialog.setTypeIcon(R.drawable.task_coin);
                    rewardDialog.setBtnText("好的");
                    rewardDialog.hideAppLayoutChilds();
                    rewardDialog.setBtnOnClickListerner(v -> {
                        rewardDialog.dismiss();
                        back();
                    });
                    rewardDialog.setCloseBtnOnClickListerner(v -> {
                        rewardDialog.dismiss();
                        back();
                    });
                    rewardDialog.show();

                    CJWatcher.getInstance().removeWatch(data.package_name);//移除监听
                });
            } else {
                mActivity.runOnUiThread(() -> {
                    waitDialog.dismiss();
                    CJCore.Toast(mContext, "网络错误", false);
                });
            }
        }).start();
    }

    private void download() {
        mActivity.runOnUiThread(() -> {
            CJCore.Toast(mContext,"开始下载",false);
        });
        task_begin.setEnabled(false);
        task_begin.setBackground(getResources().getDrawable(R.drawable.radius_30_gray));
        //开始下载
        CJDownloadLimitManager.getInstance().download(data.apk_url);
//        CJDefer.getInstance().getDefer().when(() -> {
//            taskInfo.data = null;
//            taskInfo.downloadSize = 0;
//            taskInfo.totalSize = 0;
//            taskInfo.isOverwrite = true;
//            taskInfo.savePath = CJTaskCenter.getInstance().getApkFloder(data.apk_url);
//            taskInfo.url = data.apk_url;
//            CJLogger.v("sava path :" + taskInfo.savePath);
//            CJHttp.getInstance().download(taskInfo, new CJHttpDownloadListner() {
//                @Override
//                public void onFailed(CJHttpDownloadInfo CJDownloadInfo, CJHttpError error) {
//                    taskInfo = CJDownloadInfo;
//                    CJLogger.v("CJDownloadInfo:" + taskInfo.url);
//                    CJEvent.TaskTry.getEventtBus().post(new CJEventObject(CJEventObjectType.Download_failed, null));
//                }
//
//                @Override
//                public void onProgress(CJHttpDownloadInfo CJDownloadInfo) {
//                    taskInfo = CJDownloadInfo;
//                    CJEvent.TaskTry.getEventtBus().post(new CJEventObject(CJEventObjectType.DownLoad_ing, null));
//                }
//
//                @Override
//                public void onSuccess(CJHttpDownloadInfo CJDownloadInfo) {
//                    taskInfo = CJDownloadInfo;
//                    CJEvent.TaskTry.getEventtBus().post(new CJEventObject(CJEventObjectType.DownLoad_sucess, null));
//                }
//            });
//        });
    }

    private void loadData() {
//        waitDialog.show();
        new Thread(() -> {
            boolean ret = CJZManager.getInstance().tryPlaceGetDetail(tid);
            if (ret) {
                data = CJTryPlaceHelper.getInstance().getDetailModel();
                Collections.sort(data.sections);//小到大排序
//                data.sections.get(1).days = 3;
//                data.sections.get(2).days = 5;
//                CJEvent.TaskTry.getEventtBus().post(new CJEventObject(CJEventObjectType.LoadFinish, null));
                myHandler.sendEmptyMessage(LoadFinish);
            } else {
                mActivity.runOnUiThread(() -> {
                    back();
                    CJCore.Toast(mContext, "网络错误", false);
                });
            }
        }).start();
        ;
    }


    @Override
    public void getMessage(Message msg) {
        if (msg == null) return;
        switch (msg.what) {
            case LoadFinish: {
                CJLogger.v("LoadFinish");
                waitDialog.dismiss();
                initUi();
            }
            break;
            case LoadFailed: {
                CJLogger.v("LoadFailed");
                waitDialog.dismiss();
            }
            break;
            case Download_failed: {
                CJCore.Toast(mContext, "下载失败", false);
                CJFile.deleteSingleFile(taskInfo.savePath);
                task_begin.setEnabled(true);
                task_begin.setBackground(getResources().getDrawable(R.drawable.radius_30_theme));
            }
            break;
            case DownLoad_sucess: {
                CJWatcher.getInstance().putWatch(data.package_name);
                CJPackage.installApk(mContext, taskInfo.savePath);
                task_begin.setEnabled(true);
            }
            break;
            case DownLoad_ing: {
//                signDialog.setBtnText(CJFile.getFileSieze(taskInfo.downloadSize) + "/" + CJFile.getFileSieze(taskInfo.totalSize));
                CJLogger.v("download size:" + taskInfo.downloadSize + "total size:" + taskInfo.totalSize);
                float progress = taskInfo.downloadSize / (taskInfo.totalSize * 1f);
                CJLogger.v("progress:" + progress);
                progress = progress * 100;
                progressBar.setProgress((int) progress);

                task_begin.setEnabled(false);
            }
            break;
            case Download:{
                info = (CJDownloadInfo)msg.obj;
                if (info.getUrl() != data.apk_url){
                    return;
                }
                if (CJDownloadInfo.DOWNLOAD.equals(info.getDownloadStatus())){
//                    downloadInfo = info;
                    if (info.getTotal() == 0){
                        progressBar.setProgress(0);
                    }else{
                        float progress = info.getProgress() * progressBar.getMax() / info.getTotal();
                        progressBar.setProgress((int) progress);
                    }
                    tx_begin_text.setText("暂停");
                    task_begin.setEnabled(true);
                    task_begin.setBackground(getResources().getDrawable(R.drawable.radius_30_theme));

                }else if (CJDownloadInfo.DOWNLOAD_OVER.equals(info.getDownloadStatus())){
                    CJCore.Toast(mContext,"下载完成",false);
                    progressBar.setProgress(progressBar.getMax());
                    tx_begin_text.setText("安装");
                    task_begin.setEnabled(true);
                    task_begin.setBackground(getResources().getDrawable(R.drawable.radius_30_theme));
                }
                else if (CJDownloadInfo.DOWNLOAD_PAUSE.equals(info.getDownloadStatus())){

//                    Toast.makeText(this,"下载暂停",Toast.LENGTH_SHORT).show();
                    tx_begin_text.setText("继续下载");
                    task_begin.setEnabled(true);
                    task_begin.setBackground(getResources().getDrawable(R.drawable.radius_30_theme));

                }
//                else if (CJDownloadInfo.DOWNLOAD_CANCEL.equals(info.getDownloadStatus())){
//
//                    progressBar.setProgress(0);
//                    Toast.makeText(this,"下载取消",Toast.LENGTH_SHORT).show();
//
//                }
                else if (CJDownloadInfo.DOWNLOAD_ERROR.equals(info.getDownloadStatus())){
//                    Toast.makeText(this,"下载出错",Toast.LENGTH_SHORT).show();
                    CJCore.Toast(mContext, "下载失败", false);
                    CJDownloadLimitManager.getInstance().cancelDownload(info);
                    tx_begin_text.setText("试玩");
                    task_begin.setEnabled(true);
                    task_begin.setBackground(getResources().getDrawable(R.drawable.radius_30_theme));
                    info=null;
                }
            }
            break;

            default:
                break;
        }
    }

    private void isShowCoin() {
        if (CJWatcher.getInstance().isHaveEnoughTime((long) data.sections.get(section).operate_time, data.package_name)) {
            //满足条件,上报，显示金币
            reportSectionTask(data.sections.get(section));
        } else {
            if(CJWatcher.getInstance().isHavePackage(data.package_name)){
                //不满足条件，提示需要的时间
                if(myMessageDialog != null){
                    myMessageDialog.dismiss();
                    myMessageDialog = null;
                }
                myMessageDialog = MessageDialog.dialogShow(mActivity,mContext, "任务未完成"
                        , "还需试玩 【" + data.apk_name + "】 "
                                + CJWatcher.getInstance().needTime((long) data.sections.get(section).operate_time, data.package_name) + "秒");
            }
        }
    }

    private boolean isNotDone(int state) {
        if (state == STATE_Done || STATE_Finish == state) {
            return false;
        } else {
            return true;
        }
    }

    private int getSection(){
//        String first = CJTime.getTimeFormatMMDD(data.apply_at * 1000);
//        String second = CJTime.getTimeFormatMMDD((data.apply_at + 1 * 24 * 60 * 60) * 1000);
//        String thirth = CJTime.getTimeFormatMMDD((data.apply_at + 1 * 24 * 60 * 60) * 1000);
        String now = CJTime.getTimeFormatMMDD(CJTime.getCurrentTimeMillis());
        long now_stmap = CJTime.getTimestamp();

        //是否超过最大日期
        long tmp1 = CJTime.getDayStartTimestamp(data.apply_at) + ((data.sections.get(data.sections.size()-1).days-1)*24*60*60);
        long now_tmp1 = CJTime.getDayStartTimestamp(now_stmap);
        if(now_tmp1 > tmp1){
            return -1;
        }

        for(int i=0; i<data.sections.size(); i++){
            String tmp = CJTime.getTimeFormatMMDD(CJTime.getDayStartTimestamp(data.apply_at)*1000 + ((data.sections.get(i).days-1)*24*60*60 )* 1000);
            if(tmp.equals(now)){
                return i;
            }
        }

        return -2;
    }

    private boolean isTheDay(){
        int ret = getSection();
        if(ret != -1 && ret != -2){
            return true;
        }
        else{
            return false;
        }
    }

    private boolean checkUsagePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
            int mode = 0;
            mode = appOps.checkOpNoThrow("android:get_usage_stats", android.os.Process.myUid(), getPackageName());
            boolean granted = mode == AppOpsManager.MODE_ALLOWED;
            if (!granted) {
                //弹窗提示用户开启权限
                MessageDialog.dialogShow(mActivity,mContext, "权限", "根据任务需求，请开启相应权限", "去开启", new CJListener() {
                    @Override
                    public void finish(Object object) {
                        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                        startActivityForResult(intent, 1);
                    }
                });
                return false;
            }
        }
        return true;
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
            int mode = 0;
            mode = appOps.checkOpNoThrow("android:get_usage_stats", android.os.Process.myUid(), getPackageName());
            boolean granted = mode == AppOpsManager.MODE_ALLOWED;
            if (!granted) {
//                Toast.makeText(this, "请开启该权限", Toast.LENGTH_SHORT).show();
//                CJCore.Toast(mContext,"请开启该权限",false);
            }
            else{
//                CJCore.Toast(mContext,"已经开启该权限",false);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //返回该页面时 是否可以获取奖励
        if (data != null) {
            isShowCoin();
            CJWatcher.getInstance().retTime(data.sections.get(section).operate_time);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CJHandle.getInstance().unRegister(CJHanlderType.tryPlace);
        if(info != null){
            CJDownloadLimitManager.getInstance().pauseDownload(info.getUrl());//暂停下载
        }
    }

    @Override
    public void back() {
        super.back();
        CJWatcher.getInstance().stopServices();
    }
}
